<template>
  <div class="form-panel">
    <div class="form-panel_header">
      <div class="title">{{ title }}</div>
      <div class="tool" v-if="!readonly">
        <el-button @click="handleAdd" type="primary" text>添加</el-button>
      </div>
    </div>
    <div class="form-panel_con">
      <div v-for="item, index in curValue" class="con-row">
        <el-form class="form-con" :ref="el => formRefs[index] = el" label-position="top" :model="item">
          <AgelFormGrid v-if="!readonly" :items="form.baseItems" :span="12" :gutter="16"></AgelFormGrid>
          <AgelFormDesc v-else :items="form.baseItems" :column="2" :gutter="16"></AgelFormDesc>
        </el-form>
        <el-button v-if="!readonly" @click="handleDelete(index)" type="danger" text>删除</el-button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { BizContractBonusVo, defaulBonuModel } from '@/api/operation/contract/types';
import { parseTime } from '@/utils/ruoyi'
const props = defineProps({
  title: {
    type: String,
    default: '基础分成'
  },
  modelValue: {
    type: Array,
    default: () => []
  },
  readonly: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue']);

const curValue = computed<Array<BizContractBonusVo>>({
  get: () => {
    if (props.modelValue && props.modelValue.length > 0) {
      (props.modelValue as Array<BizContractBonusVo>).forEach(it => {
        if (it.startFrom && it.endTo) {
          it.range = [it.startFrom, it.endTo]
        } else {
          it.range = []
        }
      })
      return props.modelValue
    } else {

      return [defaulBonuModel()]
    }
  },
  set: (val) => {
    (val || []).forEach(it => {
      if (it.range && it.range.length > 0) {
        it.startFrom = it.range[0]
        it.endTo = it.range[1]
      } else {
        it.startFrom = ''
        it.endTo = ''
      }
    })
    emits('update:modelValue', val);
  }
});

watch(() => curValue.value, async val => {
  (val || []).forEach(it => {
    if (it.range && it.range.length > 0) {
      it.startFrom = it.range[0]
      it.endTo = it.range[1]
    } else {
      it.startFrom = ''
      it.endTo = ''
    }
  })
  emits('update:modelValue', val);
}, { deep: true, immediate: true });

const formRefs = ref([]) as Ref<string[]>

const form = reactive({
  baseItems: [
    {
      prop: "range", label: "时间范围（合同有效期内）", required: true, slot: 'el-date-picker',
      attrs: { startPlaceholder: '开始日期', endPlaceholder: '结束日期', type: 'daterange', valueFormat: 'YYYY-MM-DD HH:mm:ss' },
      viewFormat: ({ modelValue }: any) => {
        return modelValue && modelValue.length ? parseTime(modelValue[0], '{y}-{m}-{d}') + ' ~ ' + parseTime(modelValue[1], '{y}-{m}-{d}') : '-'
      }
    },
    { prop: "bonusRatio", label: "分成比例（%）", required: true, attrs: { type: 'number' } },
  ],
})

const validate = () => {
  return new Promise<boolean>((resolve, reject) => {
    formRefs.value.forEach(el => {
      el.validate((valid, fields) => {
        if (valid) {
          resolve(true)
        } else {
          resolve(false)
        }
      })

    });
  })
}

const handleAdd = () => {
  let model=defaulBonuModel();
  model.startFrom=curValue.value[curValue.value.length-1].endTo;
  model.endTo=curValue.value[curValue.value.length-1].endTo;
  curValue.value.push(model)
}
const handleDelete = (index) => {
  curValue.value.splice(index, 1)
}
defineExpose({ validate })

</script>
<style lang="scss" scoped>
.form-panel {
  width: 100%;
  background: #F6F7FB;

  &_header {
    width: 100%;
    display: flex;
    padding: 8px 16px;

    .title {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-weight: 500;
      color: #323A45;
    }

  }

  &_con {
    width: 100%;

    .con-row {
      width: 100%;
      display: flex;
      overflow: hidden;
      padding: 8px 16px 16px;
      align-items: end;
    }

    .form-con {
      flex: 1;
      overflow: hidden;
      margin-right: 12px;
    }
  }

}
</style>